package com.example.petstore.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.*;
import com.example.petstore.mapper.*;
import com.example.petstore.util.ZFBqrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service("orderService")
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private LineItemMapper lineItemMapper;

    public void updateIssendByOrderId(int orderId) {
        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("orderid", orderId).set("issend", true);
        orderMapper.update(null, updateWrapper);
    }

    public Map<String, List<Order>> groupPaidOrdersByYearAndMonth() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ispay", true);

        List<Order> allOrders = orderMapper.selectList(queryWrapper);
        Map<String, List<Order>> paidOrdersByYearMonth = new LinkedHashMap<>();

        // 将订单按年月份分组并按时间排序
        allOrders.forEach(order -> {
            String yearMonth = order.getOrderDate().getYear() + "-" + order.getOrderDate().getMonthValue();

            List<Order> orders = paidOrdersByYearMonth.getOrDefault(yearMonth, new ArrayList<>());
            orders.add(order);
            orders.sort(Comparator.comparing(Order::getOrderDate)); // 对订单列表按时间排序
            paidOrdersByYearMonth.put(yearMonth, orders);
        });

        return paidOrdersByYearMonth;
    }


    //根据年月获取当月订单
    public List<Order> findByYearAndMonth(int year, int month) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.apply("YEAR(orderdate) = {0} AND MONTH(orderdate) = {1}", year, month);
        return orderMapper.selectList(queryWrapper);
    }
    public List<Order> getAllOrders() {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        return orderMapper.selectList(queryWrapper);
    }

    public CommonResponse<List<Order>> getOrdersByStatus(int isPay, int isSend, int isGet, int isReturn, int isCancel) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();

        if (isPay == 1) {
            queryWrapper.eq(Order::isIspay, 1);
        }
        if (isSend == 1) {
            queryWrapper.eq(Order::isIssend, 1);
        }
        if (isGet == 1) {
            queryWrapper.eq(Order::isIsget, 1);
        }
        if (isReturn == 1) {
            queryWrapper.eq(Order::isIsreturn, 1);
        }
        if (isCancel == 1) {
            queryWrapper.eq(Order::isIscancel, 1);
        }
        return  CommonResponse.creatForSuccess(orderMapper.selectList(queryWrapper));
    }





    public CommonResponse userBuyItemAtOnce(String username, String itemId, int number) {
//        调整库存
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        List<Item> items = itemMapper.selectList(queryWrapper);
        if(items.size() > 0){
            Item item = items.get(0);
            if(item.getQty() - number >= 0){
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("itemid", itemId);
                updateWrapper.set("qty", item.getQty() - number);
                int result = itemMapper.update(updateWrapper);
                if(result != 1){
                    return CommonResponse.creatForError("出错了，请稍后再试。");
                }
            }else{
                return CommonResponse.creatForError("库存不足");
            }
        }else {
            return CommonResponse.creatForError("出错了，请稍后再试。");
        }

        Order order = new Order();
//        System.out.println(tempOrder);
//        tempOrder.setUsername(username);
        OrderInit(order, username);
        orderMapper.insert(order);

        LineItem lineItem = new LineItem();
        lineItem.setOrderid(order.getOrderid());
        lineItem.setLineNum(1);
        lineItem.setLineNum(number);

        lineItem.setUnitprice(countUnitprice(itemId));

        return CommonResponse.creatForSuccess(order);
    }

    public CommonResponse userBuyCartItem(String username){
        Order order = new Order();
        OrderInit(order, username);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        List<CartItem> cartItemList = cartItemMapper.selectList(queryWrapper);
        int i = 1;
        int orderid = order.getOrderid();
//        List<LineItem> lineItems = new ArrayList<>();
        for(CartItem cartItem : cartItemList){
            queryWrapper = new QueryWrapper();
            queryWrapper.eq("itemid", cartItem.getItemid());
            Item item = itemMapper.selectOne(queryWrapper);
            if(item != null){
                if(item.getQty() < cartItem.getQuantity()){
                    return CommonResponse.creatForError(cartItem.getItemid() + "库存不足");
                }
            }else{
                return CommonResponse.creatForError("出错了，请稍后再试");
            }
        }

        for(CartItem cartItem : cartItemList){
            LineItem lineItem = new LineItem();
            lineItem.setOrderid(orderid);
            lineItem.setLineNum(i);
            i++;
            lineItem.setItemid(cartItem.getItemid());
            lineItem.setQuantity(cartItem.getQuantity());
//            找到原来库存
            QueryWrapper queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("itemid", cartItem.getItemid());
            Item item = itemMapper.selectOne(queryWrapper2);
//            更新库存
            UpdateWrapper updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("itemid", cartItem.getItemid());
            updateWrapper.set("qty", item.getQty() - cartItem.getQuantity());
            itemMapper.update(updateWrapper);

            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("itemid", cartItem.getItemid());
            Item item1 = itemMapper.selectOne(queryWrapper1);

            lineItem.setUnitprice(item1.getListprice());
            lineItemMapper.insert(lineItem);
        }
        cartItemMapper.delete(queryWrapper);/*不确定是否生效*/
        return CommonResponse.creatForSuccess(order);
    }

    private double countUnitprice(String itemId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("itemid", itemId);
        Item item = itemMapper.selectOne(queryWrapper);
        return item.getListprice();
    }

    private void OrderInit(Order order, String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        QueryWrapper seqw = new QueryWrapper<>();
        seqw.eq("name", "ordernum");
        Sequence sequence = sequenceMapper.selectOne(seqw);

        order.setOrderid(sequence.getNextid());

        UpdateWrapper updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", "ordernum");
        updateWrapper.set("nextid", sequence.getNextid() + 1);
        sequenceMapper.update(updateWrapper);

        order.setUsername(username);
        order.setOrderDate(LocalDateTime.now().toLocalDate());
        order.setShipaddr1(userInfo.getAddr1());
        order.setShipaddr2(userInfo.getAddr2());
        order.setShipcity(userInfo.getCity());
        order.setShipstate(userInfo.getState());
        order.setShipzip(userInfo.getZip());
        order.setShipcountry(userInfo.getCountry());
        order.setBilladdr1(userInfo.getAddr1());
        order.setBilladdr2(userInfo.getAddr2());
        order.setBillcity(userInfo.getCity());
        order.setBillstate(userInfo.getState());
        order.setBillzip(userInfo.getZip());
        order.setBillcountry(userInfo.getCountry());
//        order.setCourier(userInfo.get);
//        todo:totalprice没算
        order.setBilltofirstname(userInfo.getFirstname());
        order.setBilltolastname(userInfo.getLastname());
        order.setShiptofirstname(userInfo.getFirstname());
        order.setShiptolastname(userInfo.getLastname());
        order.setCardtype("999 9999 9999 9999");
        order.setCardtype("Visa");
        order.setLocale("CA");
        order.setIspay(false);
        order.setIssend(false);
        order.setSendnumber(null);
        order.setIsget(false);
        order.setIsreturn(false);
//        todo:
    }

    public CommonResponse userFindNoShipOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        queryWrapper.eq("issend", 0);
        List<Order> orderLine = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orderLine);
    }

    public CommonResponse getUserOrderList(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse<List<Order>> userFindShipOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("issend", 1);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse<List<Order>> userFindNoPayOrder(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("ispay", 0);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        return CommonResponse.creatForSuccess(orders);
    }

    public CommonResponse getQRCode(Order order) {
        try{
            String qr = ZFBqrUtil.getQR(order.getTotalprice());
            return CommonResponse.creatForSuccess(qr);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResponse.creatForError("二维码获取失败");
        }
    }

    /*
    * 用户删除/取消未支付订单 test ok
    * */
    public CommonResponse userDeleteOrder(int orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if(orders.size() > 0){
            Order order = orders.get(0);
            boolean ispay = order.isIspay();
            if(ispay){
                return CommonResponse.creatForError("订单已经付款无法取消");
            }

            List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
            UpdateWrapper updateWrapper;
            QueryWrapper queryWrapper1;
            for(LineItem lineItem : lineItems){
                queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("itemid", lineItem.getItemid());
                Item item = itemMapper.selectOne(queryWrapper1);

                updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("itemid", lineItem.getItemid());
                updateWrapper.set("qty", item.getQty() + lineItem.getQuantity());
                itemMapper.update(updateWrapper);
            }
//            lineItemMapper.delete(queryWrapper);

            updateWrapper = new UpdateWrapper();
            updateWrapper.eq("orderid", orderId);
            updateWrapper.set("iscancel", 1);
            orderMapper.update(updateWrapper);
            return CommonResponse.creatForSuccessMessage("取消成功");
        }
        return CommonResponse.creatForError("出错了，请稍后再试");
    }

    public CommonResponse userReturnOrder(int orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        List<Order> orders = orderMapper.selectList(queryWrapper);
        if(orders.size() > 0){
            Order order = orders.get(0);
            boolean ispay = order.isIspay();
            if(!ispay){
                return CommonResponse.creatForError("订单未付款无法退货");
            }

            List<LineItem> lineItems = lineItemMapper.selectList(queryWrapper);
            UpdateWrapper updateWrapper;
            QueryWrapper queryWrapper1;
            for(LineItem lineItem : lineItems){
                queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("itemid", lineItem.getItemid());
                Item item = itemMapper.selectOne(queryWrapper1);

                updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("itemid", lineItem.getItemid());
                updateWrapper.set("qty", item.getQty() + lineItem.getQuantity());
                itemMapper.update(updateWrapper);
            }
//            lineItemMapper.delete(queryWrapper);

            updateWrapper = new UpdateWrapper();
            updateWrapper.eq("orderid", orderId);
            updateWrapper.set("isreturn", 1);
            orderMapper.update(updateWrapper);
            return CommonResponse.creatForSuccessMessage("退货成功");
        }
        return CommonResponse.creatForError("出错了，请稍后再试");
    }
    public CommonResponse getOrderListByKey(String keyWord) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", keyWord).or().like("orderid", keyWord);
        List<Order> orderList = orderMapper.selectList(queryWrapper);
        System.out.println(orderList);
        return CommonResponse.creatForSuccess(orderList);
    }

    public CommonResponse deleteOrderById(String orderId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderid", orderId);
        if(orderMapper.delete(queryWrapper) == 1) {
            lineItemMapper.delete(queryWrapper);
            return CommonResponse.creatForSuccess();
        }
        else {
            return CommonResponse.creatForError();
        }
    }
}

